package com.zff.rental.common;

import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 分页入参
 *
 * @author HCY
 */
@Data
public class PageParams implements Serializable {
    /**
     * 页码 以1开始
     */
    protected Integer page;

    /**
     * 每页大小
     */
    protected Integer size;

    /**
     * 检查分页接口入参是否正确
     */
    public void assertPageParams() {
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null) {
            size = Integer.MAX_VALUE;
        }

        if (!verifyNumber() || !verifySize()) {
            // 入参错误
            throw new BusinessException(ResultCode.IN_PARAMETERS_ERROR);
        }
    }

    public boolean verifyNumber() {
        return page != null && page > 0;
    }

    public boolean verifySize() {
        return size != null && size > 0;
    }

    /**
     * 生成查询数据库的Pageable
     */
    public Pageable generatePageable() {
        assertPageParams();
        return PageRequest.of(page - 1, size);
    }

    /**
     * 生成查询数据库的Pageable
     */
    public Pageable generatePageable(Sort sort) {
        assertPageParams();
        return PageRequest.of(page - 1, size, sort);
    }

    /**
     * 生成排序对象
     */
    public Sort generateSort(List<SortParams> sort) {
        if (sort == null) {
            return null;
        }
        List<Sort.Order> collect = sort.stream()
                .filter(Objects::nonNull)
                .filter(vo -> Objects.nonNull(vo.getProperty()))
                .map(vo -> {
                    Sort.Direction direction = Objects.equals(vo.getIsDesc(), Boolean.TRUE) ? Sort.Direction.DESC : Sort.Direction.ASC;
                    return new Sort.Order(direction, vo.getProperty());
                }).collect(Collectors.toList());
        if (collect.isEmpty()) {
            return null;
        } else {
            return Sort.by(collect);
        }
    }
}
